/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.excel.convert;

import cn.hutool.core.util.StrUtil;
import cn.star.framework.core.dict.EnumEntry;
import cn.star.framework.excel.config.ReadWriteConstant;
import cn.star.framework.excel.core.Column;
import cn.star.framework.excel.enhance.GlobalConverterRegister;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.write.executor.AbstractExcelWriteExecutor;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import java.util.List;
import java.util.Map;

/**
 * {@link ValueWrapper}统一转换<br>
 * {@link AbstractExcelWriteExecutor#doConvert(CellWriteHandlerContext)}<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
public class ValueWrapperConverter implements Converter<ValueWrapper<?>> {
  public static final ValueWrapperConverter INSTANCE = new ValueWrapperConverter();

  @Override
  public Class<?> supportJavaTypeKey() {
    return ValueWrapper.class;
  }

  /**
   * 单元格内容转换为数据
   *
   * @param cellData
   * @param contentProperty
   * @param globalConfiguration
   * @return
   */
  @Override
  public ValueWrapper<?> convertToJavaData(
      ReadCellData<?> cellData,
      ExcelContentProperty contentProperty,
      GlobalConfiguration globalConfiguration) {

    // 实则在永远不会调用执行

    return new ValueWrapper<>(cellData.getData());
  }

  /**
   * 转换为单元格内容
   *
   * @param valueWrapper
   * @param contentProperty
   * @param globalConfiguration
   * @return
   * @throws Exception
   */
  @Override
  @SuppressWarnings({"unchecked", "rawtypes"})
  public WriteCellData<?> convertToExcelData(
      ValueWrapper<?> valueWrapper,
      ExcelContentProperty contentProperty,
      GlobalConfiguration globalConfiguration)
      throws Exception {
    Object value = valueWrapper.getValue();
    Column column = valueWrapper.getColumn();
    if (column != null) {
      CellValueConverter converter = column.getConverter();
      if (converter != null) {
        String v = converter.convert(column, valueWrapper);
        return new WriteCellData(v);
      }
    }
    Map<Boolean, List<String>> booleanValues = ReadWriteConstant.getBooleanValues();
    if (value == null) {
      // 转换空值
      return new WriteCellData<>(StrUtil.EMPTY);
    } else if (value instanceof EnumEntry<?>) {
      // 转换枚举
      EnumEntry<?> entry = (EnumEntry<?>) value;
      String label = entry.getLabel();
      return new WriteCellData<>(label);
    } else if (value instanceof Enum<?>) {
      // 转换枚举
      Enum<?> entry = (Enum<?>) value;
      return new WriteCellData<>(entry.name());
    } else if (value instanceof Boolean) {
      if (column != null && column.getOriginal() != null) {
        String label = this.getBooleanValueLabel((boolean) value, column.getName(), booleanValues);
        return new WriteCellData<>(label);
      } else {
        return new WriteCellData<>(String.valueOf(value));
      }
    } else {
      Converter converter = GlobalConverterRegister.get(value.getClass(), null);
      // 模糊转换 转换为字符串
      if (converter == null) {
        converter = GlobalConverterRegister.get(value.getClass(), CellDataTypeEnum.STRING);
      }
      // 若还是没有找到转换函数则抛出异常
      if (converter == null) {
        throw new RuntimeException(
            "Can not find 'Converter' support class " + value.getClass().getSimpleName() + ".");
      } else {
        return converter.convertToExcelData(value, contentProperty, globalConfiguration);
      }
    }
  }

  private String getBooleanValueLabel(
      boolean value, String[] labels, Map<Boolean, List<String>> booleanValues) {
    int index = ReadWriteConstant.getBooleanValuesIndex(labels, booleanValues);

    return booleanValues.get(value).get(index);
  }
}
